<template>
    <div class="group-selector">
        <el-select v-model="selectedGroup" placeholder="选择分组" style="width: 200px; margin-right: 10px;">
            <el-option label="全部文本" :value="AllTextGroupId" />
            <el-option v-for="group in textStore.groups" :key="group.groupId" :label="group.name"
                :value="group.groupId" />
        </el-select>
        <el-checkbox v-model="editorSettingStore.addNewTextToCurrentGroup" label="自动加入当前分组"></el-checkbox>
        <el-button @click="clickAddText">添加文本</el-button>
        <el-button @click="handleEditGroup">编辑分组</el-button>
    </div>
        <el-menu v-if="selectedRows.length > 0" mode="horizontal">
                <el-menu-item index="1-1" @click="deleteSelectedRows">删除所选</el-menu-item>
                <el-menu-item index="1-2" @click="showMoveDialog = true">移动所选</el-menu-item>                
        </el-menu>
    <el-table :data="currentPageElements" @selection-change="handleSelectionChange" border stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column label="id" width="100" #default="scope" resizeable="true">
            <el-text>{{ scope.row.id }}</el-text>
        </el-table-column>
        <el-table-column resizeable='true' v-for="(item, index) in textStore.languages" width="180">
            <template #header>
                <el-row>
                    <el-col :span="18" style="text-align: center;">
                        <ButtonInput v-model="item.name"></ButtonInput>
                        <!-- <el-text>{{ item.name }}</el-text> -->
                    </el-col>
                    <el-col :span="1" style="text-align: right;">
                        <el-button link type="danger" :icon="Delete" @click="deleteLanguage(item.id)"></el-button>
                    </el-col>
                </el-row>
            </template>
            <template #default="scope">
                <el-button link @click="startEdit(scope.$index, index)" style="min-width: 180px;"
                    v-if="!isEditing(scope.$index, index)">{{ scope.row.texts[index] }}</el-button>
                <el-input v-model="scope.row.texts[index]" @blur="closeEdit" @keyup.enter="closeEdit"
                    v-if="isEditing(scope.$index, index)"></el-input>
            </template>

        </el-table-column>
        <el-table-column width="100px" fixed="right">
            <template #header>
                <el-button link type="success" @click="clickNewLanguage()" :icon="CirclePlusFilled">新语言</el-button>
            </template>
            <template #default="scope">
                <el-button link type="danger" :icon="Delete" @click="clickDeleteCurRow(scope.row.id)"></el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination layout="prev, pager, next, jumper, total" :total="filteredElements.length"
        v-model:current-page="currentPage" :page-size="pageSize">
    </el-pagination>

    <!-- 文本分组编辑弹窗 -->
    <TextGroupEditDialog v-model="showTextGroupEditDialog"/>

    <!-- 移动所选到分组弹窗 -->
    <el-dialog v-model="showMoveDialog" title="移动所选到分组">
        <div style="margin-bottom: 20px;">
            <p>已选择 {{ selectedRows.length }} 条文本</p>
        </div>
        <el-form label-width="80px">
            <el-form-item label="目标分组">
                <el-select v-model="targetGroupId" placeholder="选择目标分组">
                    <el-option label="无分组" :value="AllTextGroupId"></el-option>
                    <el-option v-for="group in textStore.groups" :key="group.groupId" :label="group.name"
                        :value="group.groupId" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="showMoveDialog = false">取消</el-button>
            <el-button type="primary" @click="moveSelectedRowsToGroup">确认移动</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang='ts'>
import { Delete, CirclePlusFilled } from '@element-plus/icons-vue';
import { ElNotification } from 'element-plus';
import { useTextStore } from "@/stores/config/configTextStore"
import TextGroupEditDialog from '@/components/dialog/TextGroupEditDialog.vue';
import { useEditorSettingStore } from "@/stores/editorSettingStore"
import { ref, toRaw, computed} from 'vue'; // 添加computed和生命周期钩子
import { AllTextGroupId } from '@/utils/struct';
const electron = require("electron")
let textStore = useTextStore()
const editorSettingStore = useEditorSettingStore()

const selectedRows = ref<Array<any>>([])
let editingRow = ref(-1);
let editingCol = ref(-1);
let saveTextData = function () {
    electron.ipcRenderer.invoke('saveTextStore', toRaw(textStore.$state));
}
let clickAddText = function () {
    let text = textStore.newText()

    // 新增分组关联逻辑
    if (editorSettingStore.addNewTextToCurrentGroup && selectedGroup.value !== AllTextGroupId) {
        // 如果自动加入且未选择分组，则选择第一个分组
        let groupId = selectedGroup.value;
        const currentGroup = textStore.groups.find(g => g.groupId === groupId)
        if (currentGroup) {
            currentGroup.elementIds.push(text.id)
        }
    }
    saveTextData()
}

let clickNewLanguage = function () {
    textStore.newLanguage()
}

let currentPage = ref(1)
let pageSize = ref(10)
const selectedGroup = ref(-1);
const showGroupDialog = ref(false);
const newGroupName = ref('');
const newGroupDesc = ref('');
// 编辑分组相关状态
const showTextGroupEditDialog = ref(false);
// 移动分组对话框状态
const showMoveDialog = ref(false);
const targetGroupId = ref<number | null>(null);

const filteredElements = computed(() => {
    if (selectedGroup.value === -1) return textStore.elements;
    const group = textStore.groups.find(g => g.groupId === selectedGroup.value);
    return group ? textStore.elements.filter(e => group.elementIds.includes(e.id)) : [];
});

const currentPageElements = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    return filteredElements.value.slice(start, start + pageSize.value); // 改为使用filteredElements
});

// 处理选择变化
const handleSelectionChange = (rows: Array<any>) => {
    selectedRows.value = rows;
};

// 修改删除行逻辑
let clickDeleteCurRow = function (textId: number) {
    textStore.deleteText(textId)
    saveTextData()
}

// 移动文本到指定分组
const moveTextToGroup = (textId: number, targetGroupId: number) => {
    // 从所有分组中移除该文本
    textStore.groups.forEach(group => {
        group.elementIds = group.elementIds.filter(id => id !== textId);
    });

    // 添加到目标分组
    const targetGroup = textStore.groups.find(g => g.groupId === targetGroupId);
    if (targetGroup) {
        targetGroup.elementIds.push(textId);
        saveTextData();
    }
}

let isEditing = function (row: number, col: number) {
    return editingRow.value == row && editingCol.value == col;
}
let startEdit = function (index: number, colIndex: number) {
    editingRow.value = index
    editingCol.value = colIndex
}
let closeEdit = function () {
    let text = textStore.elements[pageSize.value * (currentPage.value - 1) + editingRow.value]

    textStore.getText(text.id)!!.texts[editingCol.value] = text.texts[editingCol.value]
    editingRow.value = -1;
    editingCol.value = -1;
    saveTextData()
}
const createNewGroup = () => {
    if (newGroupName.value) {
        textStore.createGroup(newGroupName.value, newGroupDesc.value);
        showGroupDialog.value = false;
        newGroupName.value = '';
        newGroupDesc.value = '';
    }
};

// 处理编辑分组按钮点击
const handleEditGroup = () => {
    console.log('handleEditGroup');
    showTextGroupEditDialog.value = true;
};

// 处理分组刷新事件
const handleRefreshGroups = () => {
    // 分组已在textStore中更新，这里可以添加额外的处理逻辑
    console.log('分组已刷新');
};

// 删除所选行
const deleteSelectedRows = () => {
    selectedRows.value.forEach(row => {
        clickDeleteCurRow(row.id);
    });
    selectedRows.value = [];
};



// 移动所选行到目标分组
const moveSelectedRowsToGroup = () => {
    if (targetGroupId.value !== null) {
        selectedRows.value.forEach(row => {
            moveTextToGroup(row.id, targetGroupId.value!);
        });
        showMoveDialog.value = false;
        selectedRows.value = [];
    } else {
        ElNotification.warning({
            title: '提示',
            message: '请先选择目标分组',
            duration: 2000
        });
    }
};

let deleteLanguage = function (id: number) {
    textStore.deleteLanguage(id)
}
</script>
<style scoped>
.group-selector {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.operation-menu {
    margin-bottom: 15px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    height: 40px;
    /* 缩小整体高度 */
}

.operation-menu :deep(.el-sub-menu__title) {
    font-size: 16px;
    padding: 0 20px 0 12px;
    /* 调整左右padding */
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    /* 匹配父容器高度 */
}

.operation-menu :deep(.el-sub-menu__icon-arrow) {
    margin-left: 8px;
    position: static;
    /* 禁用绝对定位 */
    transform: none;
    /* 重置旋转动画 */
}
</style>